﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.DirectoryServices.ActiveDirectory;
using System.Drawing;
using System.IO;
using System.Management;
using System.Net;
using System.Net.NetworkInformation;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace WinInfo
{
    public partial class Main : Form
    {
        private bool initOK = false;
        public Main()
        {
            InitializeComponent();
            txtInfo.Text = "数据加载中。。。";
            backgroundWorker.RunWorkerAsync();
        }

        private string Init()
        {
            // throw new Exception("q");
            const string FormatStr = "{0}:{1}\r\n";
            const string FormatStr3 = "{0}:{1}{2}\r\n";
            var sb = new StringBuilder();
            sb.AppendFormat(FormatStr, "电脑名称", Environment.MachineName);
            //sb.AppendFormat(FormatStr, "所属网域", Environment.UserDomainName);
            try
            {
                sb.AppendFormat(FormatStr, "域", Domain.GetComputerDomain());
            }
            catch
            {
                //sb.AppendFormat(FormatStr, "工作组", "");
            }
            sb.AppendFormat(FormatStr, "当前用户", Environment.UserName);
            sb.AppendFormat(FormatStr, ".Net Framework版本", Environment.Version);
            sb.AppendFormat(FormatStr, "系统版本", Environment.OSVersion.VersionString);
            sb.AppendFormat(FormatStr, "操作系统", getOSInfo());
            sb.AppendFormat(FormatStr, "系统平台", Environment.OSVersion.Platform.ToString());
            sb.AppendFormat(FormatStr, "系统目录", Environment.SystemDirectory);
            //sb.AppendFormat(FormatStr, "系统目录", Environment.WorkingSet);

            sb.AppendLine();
            ManagementClass mc = new ManagementClass("Win32_Processor");
            ManagementObjectCollection moc = mc.GetInstances();
            foreach (ManagementObject mo in moc)
            {
                foreach (PropertyData pd in mo.Properties)
                {
                    string name = null;
                    switch (pd.Name)
                    {
                        case "Name":
                            name = "CPU名称";
                            break;
                        case "L2CacheSize":
                            name = "CPU二级缓存(Kb)";
                            break;
                        case "L3CacheSize":
                            name = "CPU三级缓存(Kb)";
                            break;
                        case "NumberOfCores":
                            name = "CPU内核数量";
                            break;
                        case "ThreadCount":
                            name = "CPU线程数量";
                            break;
                        default:
                            continue;
                    }
                    sb.AppendFormat(FormatStr, name ?? pd.Name, pd.Value);
                }
            }
            sb.AppendLine();

            foreach (System.IO.DriveInfo drive in System.IO.DriveInfo.GetDrives())
            {
                sb.AppendFormat(FormatStr, "驱动器名称", drive.Name);
                sb.AppendFormat(FormatStr, "驱动器类型", drive.DriveType);
                if (!drive.IsReady)
                {
                    continue;
                }
                sb.AppendFormat(FormatStr, "驱动器盘符", drive.VolumeLabel);
                sb.AppendFormat(FormatStr, "驱动器格式", drive.DriveFormat);
                sb.AppendFormat(FormatStr3, "驱动器总空间", (drive.TotalSize / 1024 / 1024 / 1024).ToString(), "GB");
                sb.AppendFormat(FormatStr3, "驱动器可用空间", (drive.AvailableFreeSpace / 1024 / 1024 / 1024).ToString(), "GB");
                sb.AppendLine();
            }

            sb.AppendLine();

            var pingList = new List<string>();

            NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
            foreach (NetworkInterface network in interfaces)
            {
                sb.AppendFormat(FormatStr, "网卡名称", network.Name);
                sb.AppendFormat(FormatStr, "网卡属性", network.Description);
                sb.AppendFormat(FormatStr, "网卡类型", network.NetworkInterfaceType);
                sb.AppendFormat(FormatStr, "网卡状态", network.OperationalStatus);
                sb.AppendFormat(FormatStr, "网卡速度", network.Speed / 1024 / 1024);
                sb.AppendFormat(FormatStr, "支持多播", network.SupportsMulticast);
                sb.AppendFormat(FormatStr, "只接收流量", network.IsReceiveOnly);
                sb.AppendFormat(FormatStr, "物理地址", network.GetPhysicalAddress().ToString());
                var ipv4Info = network.GetIPv4Statistics();
                sb.AppendFormat(FormatStr3, "接收", ipv4Info.BytesReceived / 1024, "Kb");
                sb.AppendFormat(FormatStr3, "发送", ipv4Info.BytesSent / 1024, "Kb");
                var ipInfo = network.GetIPProperties();
                foreach (var item in ipInfo.DhcpServerAddresses)
                {
                    sb.AppendFormat(FormatStr, "Dhcp", item.ToString());
                }
                foreach (var item in ipInfo.DnsAddresses)
                {
                    sb.AppendFormat(FormatStr, "Dns", item.ToString());
                }
                foreach (var item in ipInfo.GatewayAddresses)
                {
                    sb.AppendFormat(FormatStr, "网关", item.Address.ToString());
                    pingList.Add(item.Address.ToString());
                }
                //foreach (var item in ipInfo.GetIPv4Properties().)
                //{
                //    sb.AppendFormat(FormatStr, "UnicastAddresses", item.Address.ToString());
                //}
                foreach (var item in ipInfo.UnicastAddresses)
                {
                    sb.AppendFormat(FormatStr, "UnicastAddresses", item.Address.ToString());
                }
                foreach (var item in ipInfo.WinsServersAddresses)
                {
                    sb.AppendFormat(FormatStr, "WinsServersAddresses", item.Address.ToString());
                }
                sb.AppendLine();
            }
            pingList.Add("www.baidu.com");
            Ping ping = new Ping();
            string pingResult = null;
            foreach (var item in pingList)
            {
                try
                {
                    pingResult = ping.Send(item).Status.ToString();
                }
                catch (Exception ex)
                {
                    pingResult = ex.Message;
                }
                sb.AppendFormat(FormatStr, "Ping " + item, pingResult);
            }

            sb.AppendLine();
            sb.AppendLine();
            sb.AppendLine();
            sb.AppendLine("Environment:");
            foreach (var item in typeof(Environment).GetProperties(BindingFlags.Public | BindingFlags.Static))
            {
                try
                {
                    sb.AppendFormat(FormatStr, item.Name, item.GetValue(null, null));
                }
                catch (Exception ex)
                {
                    sb.AppendFormat(FormatStr, item.Name, ex.Message);
                }
            }

            return sb.ToString();
        }

        private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!initOK)
            {
                MessageBox.Show("数据加载中，请耐心等待。。。", "提示");
                return;
            }
            try
            {
                SaveAsTxtFile(txtInfo.Text);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        /// <summary>
        /// 将字符串存储为txt文档格式的文件。
        /// </summary>
        /// <param name="strtext">要保存的字符串内容。</param>
        private void SaveAsTxtFile(string strtext)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Title = "请选择文件存放路径";
            sfd.FileName = "电脑信息" + DateTime.Now.ToString("yyyyMMdd");
            sfd.Filter = "文本文档(*.txt)|*.txt";
            if (sfd.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            using (StreamWriter sw = new StreamWriter(sfd.FileName, false))
            {
                sw.Write(strtext);
            }
            //Process.Start(sfd.FileName);
        }

        string getOSInfo()
        {
            //Get Operating system information.  
            OperatingSystem os = Environment.OSVersion;
            //Get version information about the os.  
            Version vs = os.Version;

            //Variable to hold our return value  
            string operatingSystem = "";

            if (os.Platform == PlatformID.Win32Windows)
            {
                //This is a pre-NT version of Windows  
                switch (vs.Minor)
                {
                    case 0:
                        operatingSystem = "95";
                        break;
                    case 10:
                        if (vs.Revision.ToString() == "2222A")
                            operatingSystem = "98SE";
                        else
                            operatingSystem = "98";
                        break;
                    case 90:
                        operatingSystem = "Me";
                        break;
                    default:
                        break;
                }
            }
            else if (os.Platform == PlatformID.Win32NT)
            {
                switch (vs.Major)
                {
                    case 3:
                        operatingSystem = "NT 3.51";
                        break;
                    case 4:
                        operatingSystem = "NT 4.0";
                        break;
                    case 5:
                        if (vs.Minor == 0)
                            operatingSystem = "2000";
                        else
                            operatingSystem = "XP";
                        break;
                    case 6:
                        switch (vs.Minor)
                        {
                            case 0:
                                operatingSystem = "Vista";
                                break;
                            case 1:
                                operatingSystem = "7";
                                break;
                            case 2:
                                operatingSystem = "8";
                                break;
                            case 3:
                                operatingSystem = "8.1";
                                break;
                            default:
                                break;
                        }
                        break;
                    case 10:
                        operatingSystem = "10";
                        break;
                    default:
                        break;
                }
            }
            //Make sure we actually got something in our OS check  
            //We don't want to just return " Service Pack 2" or " 32-bit"  
            //That information is useless without the OS version.  
            if (operatingSystem != "")
            {
                //Got something.  Let's prepend "Windows" and get more info.  
                operatingSystem = "Windows " + operatingSystem;
                //See if there's a service pack installed.  
                if (os.ServicePack != "")
                {
                    //Append it to the OS name.  i.e. "Windows XP Service Pack 3"  
                    operatingSystem += " " + os.ServicePack;
                }
                //Append the OS architecture.  i.e. "Windows XP Service Pack 3 32-bit"  
                operatingSystem += " " + getOSArchitecture().ToString() + "-bit";
            }
            //Return the information we've gathered.  
            return operatingSystem;
        }
        int getOSArchitecture()
        {
            string pa = Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE");
            return ((String.IsNullOrEmpty(pa) || String.Compare(pa, 0, "x86", 0, 3, true) == 0) ? 32 : 64);
        }
        private void uploadToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!initOK)
            {
                MessageBox.Show("数据加载中，请耐心等待。。。", "提示");
                return;
            }
            var vals = new NameValueCollection();
            vals.Add("info", txtInfo.Text);
            using (var webClient = new WebClient())
            {
                try
                {
                    var data = webClient.UploadValues("http://services.lizhanglong.com/services/uploadComputeInfo.ashx", vals);
                    var msg = Encoding.UTF8.GetString(data);
                    MessageBox.Show(msg, "提示");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "上传失败");
                }
            }
        }

        private void concatMeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Process.Start("http://www.lizhanglong.com/?from=computerInfo");
        }

        private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            var str = e.Result.ToString();
            txtInfo.Text = str;
            initOK = true;
        }

        private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                e.Result = Init();
            }
            catch (Exception ex)
            {
                e.Result = ex.ToString();
            }
        }
    }
}
